<template>
  <view class="xl-cache-engine">
    <!-- 组件标题 -->
    <view class="component-title">高性能本地缓存引擎</view>
    
    <!-- 状态展示区 -->
    <view class="status-section">
      <view class="status-item">
        <text class="label">引擎状态</text>
        <text class="value" :class="{ 'active': cacheEngine }">{{ cacheEngine ? '已初始化' : '未初始化' }}</text>
      </view>
      <view class="status-item">
        <text class="label">存储引擎</text>
        <text class="value">{{ config.engine === ENGINE_TYPE.SQLITE ? 'SQLite' : 'IndexedDB' }}</text>
      </view>
      <view class="status-item">
        <text class="label">加密状态</text>
        <text class="value" :class="{ 'active': config.encryption }">{{ config.encryption ? '已启用' : '未启用' }}</text>
      </view>
    </view>
    
    <!-- 统计信息 -->
    <view class="stats-section">
      <view class="stats-item">
        <text class="label">最大缓存</text>
        <text class="value">{{ (config.maxSize / (1024 * 1024)).toFixed(2) }}MB</text>
      </view>
      <view class="stats-item">
        <text class="label">过期时间</text>
        <text class="value">{{ (config.maxAge / (24 * 60 * 60 * 1000)).toFixed(1) }}天</text>
      </view>
      <view class="stats-item">
        <text class="label">最大项数</text>
        <text class="value">{{ config.maxItems }}</text>
      </view>
    </view>
    
    <!-- 操作区域 -->
    <view class="operation-section">
      <view class="operation-title">快速操作</view>
      <view class="operation-buttons">
        <button class="operation-btn" @click="handleClearCache">清空缓存</button>
        <button class="operation-btn" @click="handleSync">同步数据</button>
      </view>
    </view>
    
    <!-- 插槽内容 -->
    <slot></slot>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getDeviceInfo } from './utils/device';

// 缓存引擎类型
const ENGINE_TYPE = {
  SQLITE: 'sqlite',
  INDEXED_DB: 'indexeddb'
};

// 缓存配置
const config = {
  maxSize: 100 * 1024 * 1024, // 最大缓存大小（100MB）
  maxAge: 7 * 24 * 60 * 60 * 1000, // 最大缓存时间（7天）
  maxItems: 1000, // 最大缓存项数
  engine: ENGINE_TYPE.SQLITE, // 默认使用SQLite
  encryption: true, // 是否启用加密
  syncInterval: 5 * 60 * 1000, // 同步间隔（5分钟）
};

// 状态变量
const cacheEngine = ref(null);
const deviceInfo = ref(null);
const encryptionKey = ref(null);

// 初始化缓存引擎
const initEngine = async () => {
  try {
    // 获取设备信息
    deviceInfo.value = await getDeviceInfo();
    
    // 生成加密密钥
    if (config.encryption) {
      encryptionKey.value = generateEncryptionKey(deviceInfo.value);
    }
    
    // 根据平台选择缓存引擎
    if (config.engine === ENGINE_TYPE.SQLITE) {
      // #ifdef APP-PLUS
      cacheEngine.value = await initSQLite();
      // #endif
    } else {
      // #ifdef H5
      cacheEngine.value = await initIndexedDB();
      // #endif
    }
    
    return true;
  } catch (error) {
    console.error('初始化缓存引擎失败:', error);
    return false;
  }
};

// 初始化SQLite
const initSQLite = async () => {
  // #ifdef APP-PLUS
  const db = plus.sqlite.openDatabase({
    name: 'xl_cache',
    path: '_doc/xl_cache.db'
  });
  
  // 创建缓存表
  db.executeSql(`
    CREATE TABLE IF NOT EXISTS cache (
      key TEXT PRIMARY KEY,
      value TEXT,
      size INTEGER,
      timestamp INTEGER,
      version INTEGER
    )
  `);
  
  return db;
  // #endif
};

// 初始化IndexedDB
const initIndexedDB = async () => {
  // #ifdef H5
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('xl_cache', 1);
    
    request.onerror = () => reject(request.error);
    request.onsuccess = () => resolve(request.result);
    
    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      if (!db.objectStoreNames.contains('cache')) {
        db.createObjectStore('cache', { keyPath: 'key' });
      }
    };
  });
  // #endif
};

// 生成加密密钥
const generateEncryptionKey = (deviceInfo) => {
  const key = JSON.stringify(deviceInfo);
  // 使用uni-app内置的加密方法
  return uni.arrayBufferToBase64(new TextEncoder().encode(key));
};

// 加密数据
const encryptData = (data) => {
  if (!config.encryption || !encryptionKey.value) return data;
  // 使用uni-app内置的加密方法
  const jsonStr = JSON.stringify(data);
  const arrayBuffer = new TextEncoder().encode(jsonStr);
  return uni.arrayBufferToBase64(arrayBuffer);
};

// 解密数据
const decryptData = (encryptedData) => {
  if (!config.encryption || !encryptionKey.value) return encryptedData;
  try {
    // 使用uni-app内置的解密方法
    const arrayBuffer = uni.base64ToArrayBuffer(encryptedData);
    const jsonStr = new TextDecoder().decode(arrayBuffer);
    return JSON.parse(jsonStr);
  } catch (error) {
    console.error('解密数据失败:', error);
    return encryptedData;
  }
};

// 设置缓存
const set = async (key, value, options = {}) => {
  try {
    const data = {
      value: encryptData(value),
      size: JSON.stringify(value).length,
      timestamp: Date.now(),
      version: (options.version || 0) + 1
    };
    
    if (config.engine === ENGINE_TYPE.SQLITE) {
      // #ifdef APP-PLUS
      await cacheEngine.value.executeSql(
        'INSERT OR REPLACE INTO cache (key, value, size, timestamp, version) VALUES (?, ?, ?, ?, ?)',
        [key, data.value, data.size, data.timestamp, data.version]
      );
      // #endif
    } else {
      // #ifdef H5
      const transaction = cacheEngine.value.transaction(['cache'], 'readwrite');
      const store = transaction.objectStore('cache');
      await store.put({ key, ...data });
      // #endif
    }
    
    // 检查缓存大小
    await checkCacheSize();
    
    return true;
  } catch (error) {
    console.error('设置缓存失败:', error);
    return false;
  }
};

// 获取缓存
const get = async (key) => {
  try {
    let data;
    
    if (config.engine === ENGINE_TYPE.SQLITE) {
      // #ifdef APP-PLUS
      const result = await cacheEngine.value.executeSql(
        'SELECT * FROM cache WHERE key = ?',
        [key]
      );
      data = result.rows.item(0);
      // #endif
    } else {
      // #ifdef H5
      const transaction = cacheEngine.value.transaction(['cache'], 'readonly');
      const store = transaction.objectStore('cache');
      data = await store.get(key);
      // #endif
    }
    
    if (!data) return null;
    
    // 检查缓存是否过期
    if (Date.now() - data.timestamp > config.maxAge) {
      await remove(key);
      return null;
    }
    
    return decryptData(data.value);
  } catch (error) {
    console.error('获取缓存失败:', error);
    return null;
  }
};

// 删除缓存
const remove = async (key) => {
  try {
    if (config.engine === ENGINE_TYPE.SQLITE) {
      // #ifdef APP-PLUS
      await cacheEngine.value.executeSql(
        'DELETE FROM cache WHERE key = ?',
        [key]
      );
      // #endif
    } else {
      // #ifdef H5
      const transaction = cacheEngine.value.transaction(['cache'], 'readwrite');
      const store = transaction.objectStore('cache');
      await store.delete(key);
      // #endif
    }
    return true;
  } catch (error) {
    console.error('删除缓存失败:', error);
    return false;
  }
};

// 清空缓存
const clear = async () => {
  try {
    if (config.engine === ENGINE_TYPE.SQLITE) {
      // #ifdef APP-PLUS
      await cacheEngine.value.executeSql('DELETE FROM cache');
      // #endif
    } else {
      // #ifdef H5
      const transaction = cacheEngine.value.transaction(['cache'], 'readwrite');
      const store = transaction.objectStore('cache');
      await store.clear();
      // #endif
    }
    return true;
  } catch (error) {
    console.error('清空缓存失败:', error);
    return false;
  }
};

// 检查缓存大小
const checkCacheSize = async () => {
  try {
    let totalSize = 0;
    let items = [];
    
    if (config.engine === ENGINE_TYPE.SQLITE) {
      // #ifdef APP-PLUS
      const result = await cacheEngine.value.executeSql('SELECT * FROM cache ORDER BY timestamp ASC');
      for (let i = 0; i < result.rows.length; i++) {
        const item = result.rows.item(i);
        items.push(item);
        totalSize += item.size;
      }
      // #endif
    } else {
      // #ifdef H5
      const transaction = cacheEngine.value.transaction(['cache'], 'readonly');
      const store = transaction.objectStore('cache');
      const cursor = await store.openCursor();
      
      while (cursor) {
        items.push(cursor.value);
        totalSize += cursor.value.size;
        await cursor.continue();
      }
      // #endif
    }
    
    // 如果超出大小限制，删除最旧的项
    while (totalSize > config.maxSize && items.length > 0) {
      const item = items.shift();
      await remove(item.key);
      totalSize -= item.size;
    }
    
    // 如果超出数量限制，删除最旧的项
    while (items.length > config.maxItems) {
      const item = items.shift();
      await remove(item.key);
    }
  } catch (error) {
    console.error('检查缓存大小失败:', error);
  }
};

// 同步缓存
const sync = async () => {
  try {
    // 获取所有缓存项
    let items = [];
    
    if (config.engine === ENGINE_TYPE.SQLITE) {
      // #ifdef APP-PLUS
      const result = await cacheEngine.value.executeSql('SELECT * FROM cache');
      for (let i = 0; i < result.rows.length; i++) {
        items.push(result.rows.item(i));
      }
      // #endif
    } else {
      // #ifdef H5
      const transaction = cacheEngine.value.transaction(['cache'], 'readonly');
      const store = transaction.objectStore('cache');
      const cursor = await store.openCursor();
      
      while (cursor) {
        items.push(cursor.value);
        await cursor.continue();
      }
      // #endif
    }
    
    // 同步到服务器
    // TODO: 实现服务器同步逻辑
    
    return true;
  } catch (error) {
    console.error('同步缓存失败:', error);
    return false;
  }
};

// 清空缓存
const handleClearCache = async () => {
  const success = await clear();
  uni.showToast({
    title: success ? '清空成功' : '清空失败',
    icon: success ? 'success' : 'error'
  });
};

// 同步数据
const handleSync = async () => {
  const success = await sync();
  uni.showToast({
    title: success ? '同步成功' : '同步失败',
    icon: success ? 'success' : 'error'
  });
};

// 导出方法
defineExpose({
  initEngine,
  set,
  get,
  remove,
  clear,
  sync
});

// 组件挂载时初始化
onMounted(async () => {
  await initEngine();
  
  // 启动定时同步
  if (config.syncInterval > 0) {
    setInterval(sync, config.syncInterval);
  }
});
</script>

<style lang="scss">
.xl-cache-engine {
  width: 100%;
  
  .component-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 30rpx;
  }
  
  .status-section {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    margin-bottom: 30rpx;
    
    .status-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;
      background-color: #f5f5f5;
      border-radius: 10rpx;
      
      .label {
        font-size: 28rpx;
        color: #666666;
      }
      
      .value {
        font-size: 28rpx;
        color: #333333;
        font-weight: 500;
        
        &.active {
          color: #007AFF;
        }
      }
    }
  }
  
  .stats-section {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
    
    .stats-item {
      flex: 1;
      text-align: center;
      padding: 20rpx;
      background-color: #f5f5f5;
      border-radius: 10rpx;
      margin: 0 10rpx;
      
      &:first-child {
        margin-left: 0;
      }
      
      &:last-child {
        margin-right: 0;
      }
      
      .label {
        font-size: 24rpx;
        color: #666666;
        margin-bottom: 10rpx;
        display: block;
      }
      
      .value {
        font-size: 32rpx;
        color: #333333;
        font-weight: 600;
      }
    }
  }
  
  .operation-section {
    .operation-title {
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 20rpx;
    }
    
    .operation-buttons {
      display: flex;
      gap: 20rpx;
      
      .operation-btn {
        flex: 1;
        height: 80rpx;
        background-color: #007AFF;
        color: #ffffff;
        border-radius: 10rpx;
        font-size: 28rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &:active {
          opacity: 0.8;
        }
      }
    }
  }
}
</style> 